<template>
  <div class="">
    <el-upload
      :file-list="props.fileList"
      :action="uploadUrl"
      :limit="props.limit"
      :multiple="props.multiple"
      :headers="headers"
      list-type="picture-card"
      accept="image/png,image/gif,image/jpg,image/jpeg,image/webp"
      :before-upload="onBefore"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-success="onSuccess"
      :disabled="disabled"
      ref="upload_ref"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <!-- 是否展示说明文字 -->
    <div v-if="showTitle" style="color: #999; padding-top: 5px">
      最多上传{{ limit }}张，每张大小不超过10M
    </div>
    <!-- Element Plus的图片预览组件 -->
    <el-image-viewer
      v-if="viewerVisible"
      :url-list="previewList"
      @close="handleViewerClose"
    />
  </div>
</template>

<script setup>
import { ElImageViewer, ElMessage } from "element-plus";
import { BaseUrl } from "@/api/common.js";
import { useStore } from "vuex";

const store = useStore();
// 获取请求头Token
let headers = ref({
  Authorization: store.getters.token,
});
// 获取父组件传递过来的数组
let props = defineProps({
  limit: {
    type: Number,
    default: 1,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  fileList: {
    type: Array,
    default: [],
  },
  maxSize: {
    type: Number,
    default: 5242880,
  },
  uploadType: {
    type: String,
    default: "上传图片",
  },
  marginLeft: {
    type: String,
    default: "0px",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  showTitle: {
    type: Boolean,
    default: false,
  },
});
const uploadUrl = ref(BaseUrl + "/sysProperties/uploadLogo"); //上传的接口
// 接收父组件传递的方法
const $emit = defineEmits(["success", "remove"]);

const viewerVisible = ref(false); //开启图片预览
const previewList = ref([]); //预览图片列表
const fileUrlList = ref([]); //最终的图片列表

//限制图片格式及大小
const onBefore = (file) => {
  const isJPG =
    file.type === "image/jpeg" ||
    file.type === "image/png" ||
    file.type === "image/jpg" ||
    file.type === "image/webp";
  if (!isJPG) {
    ElMessage.warning("上传图片只能是 png、jpeg、jpg、webp格式!");
    return false;
  } else if (file.size > props.maxSize) {
    ElMessage.warning("上传文件不能超过限制大小");
    return false;
  }
};
//预览
const onPreview = (file) => {
  previewList.value = [file.url];
  viewerVisible.value = true;
};
//成功
const onSuccess = (res, file, fileList) => {
  console.log(res,'11111');
  if(res.success){
    handleIamge(fileList);
    $emit("success", fileList, fileUrlList.value);
  }else{
    ElMessage.error(res.msg);
    fileUrlList.value = [];
    $emit("success", [], fileUrlList.value);
  }
};
//删除
const onRemove = (file, fileList) => {
  handleIamge(fileList);
  $emit("remove", file, fileUrlList.value);
};
// 处理数据
const handleIamge = (newValue) => {
  if (newValue.length > 0) {
    fileUrlList.value = newValue.map((item) => {
      if (item.response) {
        return item.response.msg; //后端返回 的文件数据（路径）
      } else {
        return item.url;
      }
    });
  } else {
    fileUrlList.value = [];
  }
};

//关闭预览图片弹窗
const handleViewerClose = () => {
  viewerVisible.value = false;
};

const upload_ref = ref(null);

// 监听 当前上传的数据 是不是跟 最多可传的数量一致
watch(() => props.fileList, (newVal) => {
  if (upload_ref.value) {
    const uploadEl = upload_ref.value.$el;
    // 找到包含 el-upload 类的 div 元素，这里假设只有一个，实际可根据情况调整选择器
    const targetDiv = uploadEl.querySelector('.el-upload'); 
    if (newVal.length >= props.limit) {
      targetDiv.style.display = 'none';
    } else {
      targetDiv.style.display = ''; // 恢复默认显示
    }
  }
}, { immediate: true, deep: true });
</script>

<style lang="scss" scoped>
.upload-hidden {
  .el-upload__trigger {
    display: none !important; /* 彻底隐藏上传按钮 */
  }
}
.uploadIco {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  line-height: 17px !important;
  color: #999;
  .text {
    padding-top: 10px;
  }
}
</style>